# 多阶段构建：构建阶段
FROM python:3.9-slim AS builder

# 设置环境变量
ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    PIP_NO_CACHE_DIR=1

# 创建并激活虚拟环境
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"

# 安装系统依赖（仅构建时需要）
RUN apt-get update && apt-get install -y --no-install-recommends \
    gcc \
    python3-dev \
    && rm -rf /var/lib/apt/lists/*

# 复制并安装Python依赖
COPY requirements.txt .
# 单独更新pip以更好地捕获错误
RUN pip install --no-cache-dir --upgrade pip
# 单独安装依赖并使用--no-cache-dir减少缓存
RUN pip install --no-cache-dir -r requirements.txt
# 移除不需要的文件以减小镜像体积
RUN find /opt/venv -name "*.pyc" -exec rm -f {} \; 2>/dev/null || true
RUN find /opt/venv -type d -name "__pycache__" -exec rm -rf {} \; 2>/dev/null || true
RUN pip cache purge 2>/dev/null || true

# 多阶段构建：运行阶段
FROM python:3.9-slim

# 设置非root用户以增强安全性
RUN groupadd -r appuser && useradd -r -g appuser appuser

# 设置工作目录
WORKDIR /app

# 从构建阶段复制虚拟环境
COPY --from=builder /opt/venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"

# 复制应用代码（仅复制必要文件）
COPY web_app.py .
COPY templates/ templates/

# 创建必要的目录并设置权限
RUN mkdir -p uploads results \
    && chown -R appuser:appuser /app

# 切换到非root用户
USER appuser

# 设置环境变量
ENV UPLOAD_FOLDER=/app/uploads \
    RESULTS_FOLDER=/app/results

# 暴露端口
EXPOSE 5000

# 运行应用
CMD ["gunicorn", "--bind", "0.0.0.0:5000", "--workers", "2", "--timeout", "300", "web_app:app"]